﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SVM;

namespace ModelPredictPro.Predict.SVM {
    public class TrainTask : BaseSVMTask, ITask {
        #region ITask 成员

        public override void Run() {
            Parameter svm_parameter = SyncParams();

            base.OnStepChanged("Reading and scaling the train dataset file......");
            Problem train = Problem.Read(TrainSetFile);
            RangeTransform range = RangeTransform.Compute(train);
            train = range.Scale(train);
            base.OnStepChanged(string.Empty);

            base.OnStepChanged(string.Format("Parameter selecting {0} ......", Param.ParallelModeSetting.ToString()));
            double c, gamma;
            ParameterSelection.ParallelModeSetting = Param.ParallelModeSetting;
            if (string.IsNullOrEmpty(TrainValidateFile))
                ParameterSelection.Grid(train, svm_parameter, base.ParamOutFile, out c, out gamma);
            else
                ParameterSelection.Grid(train, range.Scale(Problem.Read(TrainValidateFile)),svm_parameter, base.ParamOutFile, out c, out gamma);
            Param.C = c; Param.Gamma = gamma;
            base.OnStepChanged(string.Empty);
        }

        public override IEnumerable<ITask> ReadFromTxt(string taskFileName) {
            throw new NotImplementedException();
        }

        public override void SaveToTxt(string taskFileName) {
            throw new NotImplementedException();
        }

        #endregion

        public TrainTask(ISVMPredictParam param, string TrainSetFile, string ParamOutFile) :
            this(param, TrainSetFile, null, ParamOutFile) { 
        }

        public TrainTask(ISVMPredictParam param, string TrainSetFile, string TrainValidateFile, string ParamOutFile) :
            base(TrainSetFile, TrainValidateFile, null, ParamOutFile, null) {
            base.Param = param;
            Validate();
        }
        protected void Validate() {
            ValidateFileExist("TrainSetFile", TrainSetFile);
            ValidateNewFileCanCreated("ParamOutFile", ParamOutFile);
            if (!string.IsNullOrEmpty(TrainValidateFile))
                ValidateFileExist("TrainValidateFile", TrainValidateFile);
        }

        public override string ToString() {
            return string.Format(@"SVM Train Task
Kernel Type : 【{0}】\tUse Probability : 【{1}】\tUse Parallel : 【{2}】
Train : 【{3}】
Param output : 【{4}】
{5}".Replace(@"\t", "\t"), Param.KernelType, Param.UseProbability, Param.ParallelModeSetting, TrainSetFile, ParamOutFile,
    string.IsNullOrEmpty(TrainValidateFile)?"": string.Format("Train validate : 【{0}】" ,TrainValidateFile));
        }
    }
}
